
package com.yimixian.app.goods;

import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.yimixian.app.R;
import com.yimixian.app.SystemFramework;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.common.Constants;
import com.yimixian.app.common.WebViewActivity;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.model.Banner;
import com.yimixian.app.ui.HomeHeadView;
import com.yimixian.app.ui.PlusMinusIcon;
import com.yimixian.app.util.Strings;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.Drawable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import cn.trinea.android.view.autoscrollviewpager.AutoScrollViewPager;

import java.util.List;

public class BannersView extends FrameLayout {

    @InjectView(R.id.banners_view)
    AutoScrollViewPager mBannersView;
    @InjectView(R.id.indicator_view)
    IndicatorView mIndicatorView;

    HomeHeadView.OnHeadViewClickListener mHeadViewClickListener;
    private List<Banner> mBanners;
    private float mImageRatio;
    private int mScreenWidth;
    private PagerAdapter adapter;
    private Target target;

    public BannersView(Context context) {
        super(context);
        initBannersView();
    }

    public BannersView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initBannersView();
    }

    public BannersView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initBannersView();
    }

    private void initBannersView() {
        LayoutInflater.from(SystemFramework.getInstance().getGlobalContext()).inflate(R.layout.banners_view, this);
        ButterKnife.inject(this);

        Display display = ((Activity) getContext()).getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        mScreenWidth = size.x;
    }

    private boolean listsEqual(List<Banner> lhs, List<Banner> rhs) {
        if (lhs == rhs) {
            return true;
        }

        if (lhs == null || rhs == null || lhs.size() != rhs.size()) {
            return false;
        }

        for (int i = 0; i < lhs.size(); ++i) {
            if (!TextUtils.equals(lhs.get(i).img, rhs.get(i).img)) {
                return false;
            }
            if (!TextUtils.equals(lhs.get(i).introUrl, rhs.get(i).introUrl)) {
                return false;
            }
        }

        return true;
    }

    public void bind(List<Banner> banners, HomeHeadView.OnHeadViewClickListener mHeadViewClickListener) {
        this.mHeadViewClickListener = mHeadViewClickListener;
        bind(banners);
    }

    public void bind(List<Banner> banners) {
        if (listsEqual(mBanners, banners)) {
            return;
        }

        mBanners = banners;
        mBannersView.setAdapter(adapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return mBanners.size();
            }

            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public Object instantiateItem(ViewGroup container, final int position) {
                final ImageView imageView = new ImageView(getContext());
                imageView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
                imageView.setScaleType(ImageView.ScaleType.FIT_XY);

                int size = (int)(mScreenWidth / 1.2);
                String imgUrl = DataManager.getInstance().getImageUrl(mBanners.get(position).img,size);
                Picasso picasso = Picasso.with(getContext());
                picasso.load(imgUrl).placeholder(R.drawable.pic_banner_default_bg).into(imageView);
                //保存切圆动画图片
                if(position == 0) {
                    if (target == null) {
                        target = new Target() {
                            @Override
                            public void onBitmapLoaded(Bitmap back, Picasso.LoadedFrom from) {
                                if(getContext() instanceof GoodDetailActivity){
                                    android.support.v4.app.Fragment group = ((GoodDetailActivity) getContext()).getSupportFragmentManager().findFragmentByTag(GoodDetailFragmentGroup.class.getName());
                                    if(group == null)
                                        return;
                                    GoodDetailCartFragment mFragment = (GoodDetailCartFragment) group.getChildFragmentManager().findFragmentByTag(GoodDetailCartFragment.class.getName());
                                    if(mFragment == null)
                                        return;
                                    PlusMinusIcon mPlusMinusIcon = mFragment.getmPlusMinusIcon();
                                    int screenWidth = getResources().getDisplayMetrics().widthPixels;
                                    int width = back.getWidth() > screenWidth ? screenWidth : back.getWidth();
                                    int height = back.getHeight();
                                    float radius = width < height ? width / 2 : height / 2;
                                    float centerX = width / 2;
                                    float centerY = height / 2;
                                    Bitmap bm_circle = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                                    Canvas canvas_circle = new Canvas(bm_circle);
                                    Paint paint = new Paint();
                                    paint.setAntiAlias(true);
                                    canvas_circle.drawCircle(centerX, centerY, radius, paint);
                                    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
                                    canvas_circle.drawBitmap(back, 0, 0, paint);
                                    Matrix matrix = new Matrix();
                                    float temp = getResources().getDisplayMetrics().density * 30;
                                    float ratio = width > height ? temp / height : temp / width;
                                    matrix.setScale(ratio, ratio);
                                    mPlusMinusIcon.setShowBack(Bitmap.createBitmap(bm_circle, 0, 0, width, height, matrix, false));
                                    bm_circle.recycle();
                                }
                            }

                            @Override
                            public void onBitmapFailed(Drawable errorDrawable) {
                            }

                            @Override
                            public void onPrepareLoad(Drawable placeHolderDrawable) {
                            }
                        };
                    }
                    picasso.load(imgUrl).placeholder(R.drawable.image_left_default).into(target);
                }


                if (!Strings.isNullOrEmpty(mBanners.get(position).introUrl)) {
                    imageView.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            if (mHeadViewClickListener != null){
                                mHeadViewClickListener.OnHeadViewClick(Constants.HeadViewType.Banners,
                                        position);
                                return;
                            }
                            Intent intent = new Intent(getContext(), WebViewActivity.class);
                            intent.putExtra(WebViewActivity.EXTRA_URL,
                                    mBanners.get(position).introUrl);
                            getContext().startActivity(intent);
                        }
                    });
                } else {
                    imageView.setOnClickListener(null);
                }
                container.addView(imageView);
                return imageView;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((View) object);
            }
        });
        mBannersView.setInterval(5000);
        mBannersView.startAutoScroll(5000);
        mBannersView.setScrollDurationFactor(3);
        if (mBanners.size() > 1) {
            mIndicatorView.setVisibility(View.VISIBLE);
            mIndicatorView.init(mBanners.size());
            mBannersView.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageScrolled(int position, float positionOffset,
                        int positionOffsetPixels) {
                    mIndicatorView.scroll(position, positionOffset);
                }

                @Override
                public void onPageSelected(int position) {

                }

                @Override
                public void onPageScrollStateChanged(int state) {

                }
            });
        } else {
            mIndicatorView.setVisibility(View.GONE);
        }

    }

    public void setImageRatio(float ratio) {
        mImageRatio = ratio;
    }

//    @Override
//    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        setMeasuredDimension(getMeasuredWidth(), (int) (getMeasuredWidth() / mImageRatio));
//        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mBannersView.getLayoutParams();
//        params.height = getMeasuredHeight();
//    }

    @Override
    protected void onDetachedFromWindow() {
        mBannersView.stopAutoScroll();
        super.onDetachedFromWindow();
    }

    public List<Banner> getmBanners() {
        return mBanners;
    }

    public void update(){
        if(adapter != null)
            adapter.notifyDataSetChanged();
    }

    public AutoScrollViewPager getBannersView(){
        return mBannersView;
    }
}
